<?php
/* 
 *库存列表
 */
class StockAction extends CommonAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
            $where['Product.name'] = array('like',"%".$key."%");//产品名称
            $where['Product.ename'] = array('like',"%".$key."%");//条码
            $where['Product.cas'] = array('like',"%".$key."%");
            $where['Specification.name'] = array('like',"%".$key."%");
            $where['_logic'] = "or";

            $map['_complex'] = $where;
        }
        if(!empty($_REQUEST['cat_id']))
            $map['cat_id'] = $_REQUEST['cat_id'];
        $map['number'] = array('gt',0);
    }

    public function  index() {
      parent::index('StockView');
    }

    public function add1(){
        parent::add();
    }

    public function _before_edit1(){
        import ( "@.ORG.Page" );
        //$this->assign('products',M('Product')->where('status=1')->getField('id,name'));
        $stock = M('Stock');
        $stock->getById($_REQUEST['id']);
        $pid = $stock->product_id;
        $wid = $stock->specification;
        $this->assign('warehouses',M('Warehouse')->where('status=1')->getField('id,name'));
        //enter warehouse
        $map_enter = 'product_id = '.$pid.' and specification = '.$wid;
        $count_enters = M('Buy')->where($map_enter)->count();
        $page_enters = new Page($count_enters,25);
        $enters = M('Buy')->where($map_enter)->limit($page_enters->firstRow.",".$page_enters->listRows)->findAll();
        //$sale_backs =  M('Sale_back_detail')->where('product_id = '.$pid)->limit(20)->findAll();
        //$switch_ins = M('Switch_detail')->where('product_id = '.$pid .' and to_warehouse_id = '.$wid)->limit(20)->findAll();
        //ex-warehouse
        $count_sales = M('Order_detail')->where($map_enter)->count();
        $page_sales = new Page($count_sales,25);
        $sales = M('Order_detail')->where($map_enter)->limit($page_sales->firstRow.",".$page_sales->listRows)->findAll();
        //$back_suppliers = M('Back_supplier_detail')->where('product_id = '.$pid)->limit(20)->findAll();
        //$switch_outs = M('Switch_detail')->where('product_id = '.$pid .' and from_warehouse_id = '.$wid)->limit(20)->findAll();
        $this->assign(
            array(
                'enters' => $enters,
                'page_enters' => $page_enters->show(),
                'page_sales' => $page_sales->show(),
                'sale_backs' => $sale_backs,
                'switch_ins' => $switch_ins,
                'sales' => $sales,
                'back_suppliers' => $back_suppliers,
                'switch_outs' => $switch_outs
                 )

            );
    }

    //库存历史明细
    public function detail(){
        $model = M ( 'Stock');
        $id = $_REQUEST['id'];
        if(!$id)
            $this->error("请先选择记录");
        $this->assign('vo',$model->getById ( $id ));
        $this->_before_edit1();
        $this->display();
    }

    //为控制权限操作
    public function edit1(){
        $model = M ( 'Stock');
        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        $this->assign ( 'vo', $vo );
        $this->display ();
    }


//找出重复记录
    public function unique(){
        $stock = M('Stock');
        $map = 'product_id in (select product_id from '.C('DB_PREFIX').'Stock group by product_id having count(product_id)>1)';
        $count = $stock->where($map)->order('product_id')->count();
        if($count>0){

        import ( "@.ORG.Page" );
            //创建分页对象
            if (! empty ( $_REQUEST ['listRows'] )) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = 15;//默认每页 显示15个
            }
            $p = new Page ( $count, $listRows );
            //分页查询数据
            $voList = $stock->where($map)->order(  'product_id')->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
            
            //分页跳转的时候保证查询条件
            foreach ( $map as $key => $val ) {
                if (! is_array ( $val )) {
                    if( C('URL_MODEL') == 3 ) {
                        $p->parameter .= "&$key=" . urlencode ( $val ) . "&";//url_modl=3,then add &
                    }else {
                        $p->parameter .= "$key=" . urlencode ( $val ) . "&";//url_modl !=3
                    }
                }
            }
            if ($_REQUEST['keywords']!='') {
                $p->parameter .= 'keywords='.urlencode($_REQUEST['keywords']).'&';
            }
            //分页显示
            $page = $p->show ();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
            $this->assign ( 'list', $voList );
            $this->assign ( 'sort', $sort );
            $this->assign ( 'order', $order );
            $this->assign ( 'sortImg', $sortImg );
            $this->assign ( 'sortType', $sortAlt );
            $this->assign ( "page", '<form method="get" action="" class="form-inline form-horizontal">第<input type="text" style="width:25px" name="p" value="'.$_REQUEST['p'].'">页<input type=submit value="GO" style="margin-right:5px;">'.$page.'</form>' );
        }
        Cookie::set ( '_currentUrl_', __SELF__ );
        $this->display();
    }

    public function  _before_insert() {
     if(empty($_REQUEST['product_id']))
            $this->error("请选择产品");

        $pid = $_POST['product_id'];
        $wid = $_POST['specification'];
        $rs = M('Stock')->where('product_id ='.$pid .' and specification = '.$wid )->find();
        if( !empty($rs))
            $this->error(getModelName($pid,'Product').' 库存已存在，请不要重复录入！');
    }

    /*
    public function  _before_update() {
        $pid = $_POST['product_id'];
        $wid = $_POST['warehouse_id'];
        $rs = M('Stock')->where('product_id ='.$pid .' and warehouse_id = '.$wid )->find();
        if( !empty($rs))
            $this->error(getModelName($pid,'Product').' 库存已存在，请不要重复录入！');
    }
    */

    //TODO 做成公用类
    public function import_insert() {
        header("Content-Type:text/html; charset=utf-8");
        set_time_limit(0);
        
        import('@.ORG.PHPExcel.IOFactory','','.php');
        spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别

        //处理上传文件
        if ($_FILES['upload']['name'] == '' || $_FILES['upload']['size'] <= 0)
            $this->error('请上传正确文件!');
        $ext = strtolower(substr($_FILES['upload']['name'], strrpos($_FILES['upload']['name'], '.') + 1));
        if ($ext != 'xls' && $ext != 'xlsx')
            $this->error('本功能仅支持excel');
        $filename = date('YmdHis') . '_product.xls';
        $status = move_uploaded_file($_FILES['upload']['tmp_name'], TEMP_PATH . $filename); //到temp目录
        if (!$status) {
            $this->error('上传失败，请重新上传');
            exit;
        }

        $inputFileName = TEMP_PATH . $filename;
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
        unlink(TEMP_PATH  . $filename); //上传后删除文件
        if (!$sheetData) {
            $this->error('上传数据失败或者上传的数据为空');
        }
        $this->__saveProduct($sheetData);
    }

    protected  function __saveProduct($sheetData) {
       $product = M('Stock');
        $data = array();
        $max_pid = $product->max('id');
        $i = 0; //产品计数

        //创建一个临时表，在500条数据以上时效率倍增，提高10-100倍以上
        $temp_sql = "create temporary table vm_tmp_stock (id int(11) NOT NULL auto_increment PRIMARY KEY,product_id int(11),tm varchar(100),warehouse_id int(3),number int(4), create_time int(11)
            ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 TYPE = HEAP;";
        M()->execute($temp_sql);
        $tmp_stock = M('Tmp_stock');

        foreach ($sheetData as $key => $value) {
            //$value = iconv("utf-8", "gb2312", var_export($value, true));    //转化为中文编码
            if ($key > 1) {//从第二行开始读取
                if(empty($value['A']) || empty ($value['B']) )
                   continue;
               $data = array(
                   'tm' => trim($value['A']),   //条码
                   'number' => trim($value['B']),   //数量
                   'create_time' => time()
               );
                    $pid = $tmp_stock->add($data);    //存入临时表
                if ($pid == 0) {
                    continue;
                }
            }
        }

        //连接多个表操作，获得临时表对应的几个外表的主键ID
        //TODO 取条码还是产品名称？仅选一个  暂时设仓库为青云路仓库
        $update_sql = 'Update vm_tmp_stock a ,vm_product c set a.product_id=c.id
         where a.tm=c.tm';
        M()->execute($update_sql);
        M()->execute('UPdate vm_tmp_stock set warehouse_id = 1');
        //将临时表中的新数据插入到正式的库存表 增加ignore，如果表中存在相应记录，则忽略，继续其他数据插入
        //目前 仅适用于新增库存数据。对原有库存数量不能叠加。在导入前，需清空库存 TODO.
        //产品ID为0的则不进行导入
        $insert_sql = 'insert ignore  vm_stock(product_id,warehouse_id,number)
            select product_id,warehouse_id,number from vm_tmp_stock where product_id >0
            ';
        $i = M()->execute($insert_sql);
        //drop tmp table
        M()->execute('DROP TABLE IF EXISTS vm_tmp_stock,s1,s2');
        //clear duplicate data,only fresh data
        M()->execute('create table s1
 select max(id) as id from vm_stock GROUP BY product_id,warehouse_id');

        M()->execute('CREATE TABLE `s2` (
                  `id` int(11) NOT NULL AUTO_INCREMENT,
                  PRIMARY KEY (`id`) )
                select vm_stock.* from vm_stock,s1 where s1.id = vm_stock.id');
        M()->execute('Drop table vm_stock,s1');
        M()->execute('Rename table s2 to vm_stock');

        if($i == 0)
            $this->error ("出现错误，上传0个,请重新上传");
        
        $message = '批量上传'.$i . '个产品库存';
        A('Action')->writeLog($message,'批量新增','Stock',$max_pid);
        $this->assign('jumpUrl', '__APP__/Stock/index');
        $this->success($message,false,2);
    }

}
?>
